package com.ctshk.rpc.system.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.*;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.CharUtil;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.common.utils.SnowflakeIdWorker;
import com.ctshk.rpc.system.dto.*;
import com.ctshk.rpc.system.entity.SysBigClient;
import com.ctshk.rpc.system.entity.SysSupplier;
import com.ctshk.rpc.system.entity.SysSupplierCostItem;
import com.ctshk.rpc.system.entity.SysSupplierCostItemDepartment;
import com.ctshk.rpc.system.mapper.SysSupplierCostItemDepartmentMapper;
import com.ctshk.rpc.system.mapper.SysSupplierCostItemMapper;
import com.ctshk.rpc.system.mapper.SysSupplierMapper;
import com.ctshk.rpc.system.req.*;
import com.ctshk.rpc.system.service.ISysSupplierService;
import com.ctshk.rpc.workflow.dto.ApprovalCheckDTO;
import com.ctshk.rpc.workflow.dto.ApprovalStartDTO;
import com.ctshk.rpc.workflow.service.ISysApprovalService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <p>
 * 供应商 服务实现类
 * </p>
 *
 * @author 张志朋
 * @since 2021-02-05
 */
@Slf4j
@DubboService
public class SysSupplierServiceImpl extends ServiceImpl<SysSupplierMapper, SysSupplier> implements ISysSupplierService {

    @Autowired
    private SysSupplierMapper sysSupplierMapper;

    @Autowired
    private SysSupplierCostItemMapper sysSupplierCostItemMapper;

    @Autowired
    private SysSupplierCostItemDepartmentMapper sysSupplierCostItemDepartmentMapper;

    @Autowired
    private SysPermissionServiceImpl sysPermissionService;

    @DubboReference
    private ISysApprovalService sysApprovalService;

    /**
     * 导入供应商测试代码，勿删
     * @return
     */
    @Override
    public Result addBatchSupplierTest() {
        String json = "{\n" +
                "            \"id\": \"76341670680985600\",\n" +
                "            \"supplier_id\": \"76053411631464448\",\n" +
                "            \"cost_item_id\": \"1367370369918980098\",\n" +
                "            \"cost_item\": \"機場快線\",\n" +
                "            \"contact_name\": \"張先生\",\n" +
                "            \"contact_area_code\": \"\",\n" +
                "            \"contact_mobile\": \"+852 92048181\",\n" +
                "            \"bank_name\": \"恆生銀行\",\n" +
                "            \"bank_card\": \"9204818192048181\",\n" +
                "            \"finance_contact_name\": \"張先生\",\n" +
                "            \"finance_contact_mobile\": \"+852 92048181\",\n" +
                "            \"finance_contact_email\": \"ww@12.com\",\n" +
                "            \"business_email\": \"92048181@123.com\",\n" +
                "            \"contact_fax\": \"undefined undefined\",\n" +
                "            \"contract_file\": \"\",\n" +
                "            \"other_file\": \"\",\n" +
                "            \"remark\": \"\",\n" +
                "            \"settlement_period\": \"30\",\n" +
                "            \"settlement_period_type\": \"1\",\n" +
                "            \"settlement_currency\": \"\",\n" +
                "            \"cooperation_val idity_type\": \"1\",\n" +
                "            \"cooperation_date_begin\": \"\",\n" +
                "            \"cooperation_date_end\": \"\",\n" +
                "            \"pay_method\": \"\",\n" +
                "            \"gmt_modified\": \"\",\n" +
                "            \"create_id\": \"-1\",\n" +
                "            \"modified_id\": \"\",\n" +
                "            \"is_deleted\": \"0\",\n" +
                "            \"currency_id\": \"1364538230965456898\",\n" +
                "            \"currency\": \"人民幣\",\n" +
                "            \"exchange_rate\": \"\",\n" +
                "            \"currency_json\": \"\"\n" +
                "        }";
        SysSupplierCostItem sysSupplierCostItem = JSON.parseObject(json, SysSupplierCostItem.class);
        sysSupplierCostItem.setGmtCreate(DateUtil.parseLocalDateTime("2021-06-28 20:48:54"));
        List<SysSupplier> sysSuppliers = sysSupplierMapper.selectList(new QueryWrapper<SysSupplier>().lambda()
                .eq(SysSupplier::getGmtCreate, "2021-06-28 20:48:54"));
        List<SysSupplierCostItem> list = new ArrayList<>();
        sysSuppliers.forEach(supplier->{
            SysSupplierCostItem supplierCostItem = EntityUtil.copy(sysSupplierCostItem, SysSupplierCostItem.class);
            supplierCostItem.setId(SnowflakeIdWorker.nextId());
            supplierCostItem.setSupplierId(supplier.getId());
            list.add(supplierCostItem);
        });
        sysSupplierCostItemMapper.insertBatchSomeColumn(list);
//        generatorSupplier();
        return Result.success();
    }

    private void generatorSupplier() {
        File file = new File("e:\\supplier.txt");
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int i = 0;
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        while (true) {
            try {
                if (!((i = fileInputStream.read(bytes)) != -1)) break;
            } catch (IOException e) {
                e.printStackTrace();
            }
            sb.append(new String(bytes, StandardCharsets.UTF_8));
        }
        String str = sb.toString();
        String[] split = str.split("\n");
        System.out.println("length:" + split.length);
        List<SysSupplier> suppliers = new ArrayList<>();
        sysSupplierMapper.delete(new QueryWrapper<SysSupplier>().lambda().eq(SysSupplier::getGmtCreate, "2021-06-28 19:34:48"));
        LocalDateTime now = LocalDateTime.now();
        for (int i1 = 0; i1 < split.length; i1++) {
            String line = split[i1];
            System.out.println(i1 + line);
            String regex = line.substring(0, 1);
            if (Pattern.matches("[^a-zA-Z]", regex)) {
                continue;
            }
            String[] lineArr = line.split("\t");
            // 查重系统编码
            String randomNum = CharUtil.genRandomNum(8);
            boolean flag = true;
            while (flag) {
                List<SysSupplier> sysSuppliers = sysSupplierMapper.selectList(new QueryWrapper<SysSupplier>().lambda()
                        .eq(SysSupplier::getFinanceSysCode, randomNum)
                        .select(SysSupplier::getId));
                if (CollectionUtils.isEmpty(sysSuppliers)) {
                    break;
                }
            }
            SysSupplier supplier = new SysSupplier();
            supplier.setAccountingCode(lineArr[0]);
            supplier.setCnName(lineArr[1]);
            supplier.setCityId(64384268561809409L);
            supplier.setCity("中国香港");
            supplier.setUseSys(0);
            supplier.setId(SnowflakeIdWorker.nextId());
            supplier.setCheckStatus(SupplierAddCheckStatus.REVIEW_YES.getCode());
            supplier.setStatus(SupplierStatus.ENABLE.getCode());
            supplier.setFinanceSysCode(randomNum);
            supplier.setContractFile("{\"name\":\"map.png\",\"url\":\"https://ctshk-cloud-dev.oss-cn-hongkong.aliyuncs.com/resource/web/System/supplier/file/1624006855622.png\",\"uid\":\"rc-upload-1624006651328-21\"}");
            supplier.setBusinessLicense("{\"name\":\"sbpk.png\",\"url\":\"https://ctshk-cloud-dev.oss-cn-hongkong.aliyuncs.com/resource/web/System/supplier/file/1624006858676.png\",\"uid\":\"rc-upload-1624006651328-23\"}");
            supplier.setCreateId(1344284712813568L);
            supplier.setGmtCreate(now);
            supplier.setModifiedId(1344284712813568L);
            supplier.setGmtModified(now);
            supplier.setIsDeleted(IsDeletedCode.NO.getCode());
            suppliers.add(supplier);
        }
        sysSupplierMapper.insertBatchSomeColumn(suppliers);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addSysSupplier(SysAddSupplierReq sysAddSupplierReq, Long userId, int addType) {
        // 查重供应商中文名
        QueryWrapper<SysSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysSupplier::getCnName, sysAddSupplierReq.getCnName());
        List<SysSupplier> suppliers = sysSupplierMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(suppliers)) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6004);
        }
        // 查重系统编码
        QueryWrapper<SysSupplier> codeQueryWrapper = new QueryWrapper<>();
        codeQueryWrapper.lambda().eq(SysSupplier::getFinanceSysCode, sysAddSupplierReq.getFinanceSysCode());
        if (CollectionUtils.isNotEmpty(sysSupplierMapper.selectList(codeQueryWrapper))) {
            throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6005);
        }
        // 供应商id
        long supplierId = SnowflakeIdWorker.nextId();
        SysSupplier supplier = EntityUtil.copy(sysAddSupplierReq, SysSupplier.class);
        supplier.setCreateId(userId);
        LocalDateTime now = LocalDateTime.now();
        supplier.setId(supplierId);
        supplier.setGmtCreate(now);
        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDSUPPLIER_SYSTEM.getCode(), supplierId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            supplier.setCheckStatus(SupplierAddCheckStatus.REVIEW.getCode());
            supplier.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            supplier.setCheckStatus(SupplierAddCheckStatus.SAVED.getCode());
            supplier.setStatus(SupplierStatus.DISABLE.getCode());
        }
        sysSupplierMapper.insert(supplier);
        List<AddSupplierCostItemReq> itemReqList = sysAddSupplierReq.getSupplierCostItemReqList();
        if (CollectionUtils.isNotEmpty(itemReqList)) {
            addItems(itemReqList, supplierId, userId);
        }
        return Result.success();
    }

    @Override
    public Result<SysSupplierDTO> query(Long id) {
        SysSupplier supplier = sysSupplierMapper.selectById(id);
        if (supplier == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        SysSupplierDTO sysSupplierDTO = EntityUtil.copy(supplier, SysSupplierDTO.class);
        QueryWrapper<SysSupplierCostItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("supplier_id", id);
        queryWrapper.eq("is_deleted", 0);
        List<SysSupplierCostItem> sysSupplierCostItems = sysSupplierCostItemMapper.selectList(queryWrapper);
        if (CollectionUtils.isNotEmpty(sysSupplierCostItems)) {
            List<AddSupplierCostItemReq> itemReqs = EntityUtil.copyList(sysSupplierCostItems, AddSupplierCostItemReq.class);
            for (AddSupplierCostItemReq supplierCostItem : itemReqs) {
                Long costItemId = supplierCostItem.getId();
                QueryWrapper<SysSupplierCostItemDepartment> departmentWrapper = new QueryWrapper<>();
                departmentWrapper.eq("item_id", costItemId);
                departmentWrapper.eq("is_deleted", 0);
                List<SysSupplierCostItemDepartment> departments = sysSupplierCostItemDepartmentMapper.selectList(departmentWrapper);
                if (CollectionUtils.isNotEmpty(departments)) {
                    //供应商所属部门（1个）
                    SysSupplierCostItemDepartment department = departments.get(0);
                    supplierCostItem.setSupplierCostItemDepartmentId(department.getId());//修改数据会用到
                    supplierCostItem.setDepartmentId(department.getDepartmentId());
                    supplierCostItem.setDepartmentName(department.getDepartmentName());
                    //供应商所属部门（多个）
                    List<CostItemDepartmentReq> departmentList = EntityUtil.copyList(departments, CostItemDepartmentReq.class);
                    supplierCostItem.setCostItemDepartmentReqList(departmentList);
                }
            }
            sysSupplierDTO.setSupplierCostItemReqList(itemReqs);
        }
        return Result.success(sysSupplierDTO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result editSupplier(SysAddSupplierReq req, Long userId, int addType) {
        Long supplierId = req.getId();
        SysSupplier oldsupplier = sysSupplierMapper.selectById(supplierId);
        String newCnName = req.getCnName();
        if (!newCnName.equals(oldsupplier.getCnName())) {
            // 查重中英文名
            QueryWrapper<SysSupplier> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda()
                    .eq(SysSupplier::getCnName, newCnName)
                    .ne(SysSupplier::getId, supplierId);
            if (CollectionUtils.isNotEmpty(baseMapper.selectList(queryWrapper))) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6004);
            }
        }
        SysSupplier newsupplier = EntityUtil.copy(req, SysSupplier.class);
        newsupplier.setModifiedId(userId);
        newsupplier.setGmtModified(LocalDateTime.now());
        //走审批流程
        if (addType == 2) {
            Result<ApprovalStartDTO> approvalResult = sysApprovalService.start(SystemBusinessType.RESOURCES.getCode(),
                    SysApprovalType.ADDSUPPLIER_SYSTEM.getCode(), supplierId,
                    userId, null, null);
            if (!approvalResult.isSuccess()) {
                log.error(approvalResult.getMsg());
//                throw new BusinessException(SystemError.SYS_500);
                return approvalResult;
            }
            newsupplier.setCheckStatus(SupplierAddCheckStatus.REVIEW.getCode());
            newsupplier.setStatus(SupplierStatus.DISABLE.getCode());
        }
        //仅保存
        if (addType == 1) {
            newsupplier.setCheckStatus(SupplierAddCheckStatus.SAVED.getCode());
            newsupplier.setStatus(SupplierStatus.DISABLE.getCode());
        }
        int update = sysSupplierMapper.updateById(newsupplier);
        if (update < 1) {
            throw new BusinessException(SystemError.SYS_437);
        }
        List<AddSupplierCostItemReq> itemReqList = req.getSupplierCostItemReqList();
        if (CollectionUtils.isNotEmpty(itemReqList)) {
            //  先清除原来的成本项  在新增itemReqList成本项
            List<Long> collect = itemReqList.stream().map(e -> e.getId()).collect(Collectors.toList());
            sysSupplierCostItemDepartmentMapper.delete(
                    new QueryWrapper<SysSupplierCostItemDepartment>()
                            .lambda().in(SysSupplierCostItemDepartment::getItemId, collect)
            );
            sysSupplierCostItemMapper.delete(
                    new QueryWrapper<SysSupplierCostItem>()
                            .lambda().eq(SysSupplierCostItem::getSupplierId, supplierId)
            );
            //添加新的成本项
            addItems(itemReqList, supplierId, userId);
        }
        return Result.success(supplierId);
    }

    @Override
    public PageResponse<SysSupplierQueryListDTO> queryList(SysSupplierQueryListReq req, TokenUser tokenUser) {
        Result<List<Long>> permissionResult = sysPermissionService.queryPermission(req.getMenuId(), tokenUser.getId());
        if (!permissionResult.isSuccess()) {
            SystemError result = SystemError.getDefined(permissionResult.getCode());
            throw new BusinessException(result);
        }
        //不是管理员
        if (!GlobalConstants.Role.isAdmin(tokenUser.getUsername())) {
            req.setIsNotAdmin(1);
            req.setUserIds(permissionResult.getData());
        }
        IPage<SysSupplierQueryListDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        page = sysSupplierMapper.queryList(req, page);
        List<SysSupplierQueryListDTO> records = page.getRecords();
        PageResponse<SysSupplierQueryListDTO> result = new PageResponse<>(records, page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    @Override
    public Result<List<QuerySupplierAndAgentDTO>> querySupplierAndAgent(String name) {
        List<QuerySupplierAndAgentDTO> list = sysSupplierMapper.querySupplierAndAgent(
                name, SupplierAddCheckStatus.REVIEW_YES.getCode(),
                IsDeletedCode.NO.getCode(), SupplierStatus.ENABLE.getCode());
        return Result.success(list);
    }

    @Override
    public Result<List<QuerySupplierByNameDTO>> querySupplierByName(String name, String costItemId) {
        List<SysSupplier> list = sysSupplierMapper.querySupplierByNameAndCostItem(name, costItemId,
                SupplierAddCheckStatus.REVIEW_YES.getCode(),
                IsDeletedCode.NO.getCode(), SupplierStatus.ENABLE.getCode());
        List<QuerySupplierByNameDTO> nameList = EntityUtil.copyList(list, QuerySupplierByNameDTO.class);
        return Result.success(nameList);
    }

    @Override
    public Result<PageResponse<SearchSupplierDTO>> searchByName(SearchSupplierReq req) {
        //只搜索审批通过并且有效的供应商
        req.setCheckStatus(SupplierAddCheckStatus.REVIEW_YES.getCode());
        req.setStatus(SupplierStatus.ENABLE.getCode());

        IPage<SearchSupplierDTO> page = new Page<>(req.getPageNo(), req.getPageSize());
        page = sysSupplierMapper.searchByName(req, page, IsDeletedCode.NO.getCode());
        PageResponse<SearchSupplierDTO> result = new PageResponse<>(page.getRecords(), page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return Result.success(result);
    }

    @Override
    public Result<PageResponse<SearchSupplierDTO>> searchByNameAll(SearchSupplierReq req) {
        QueryWrapper<SysSupplier> qw = new QueryWrapper<>();
        qw.lambda().eq(SysSupplier::getIsDeleted, IsDeletedCode.NO.getCode())
                .like(SysSupplier::getCnName, req.getName());
        Page<SysSupplier> page = new Page<>(req.getPageNo(), req.getPageSize());
        Page<SysSupplier> ssp = baseMapper.selectPage(page, qw);
        List<SearchSupplierDTO> ts = new ArrayList<>();
        //为什么要重新定义SearchSupplierDTO并且改名字GroupCnName闲的蛋疼？
        for (SysSupplier item : ssp.getRecords()) {
            SearchSupplierDTO ssd = new SearchSupplierDTO();
            ssd.setId(item.getId());
            ssd.setGroupCnName(item.getCnName());
            ts.add(ssd);
        }
        PageResponse<SearchSupplierDTO> result = new PageResponse<>(ts, page.getCurrent() == 1,
                page.getTotal() <= (page.getCurrent() * page.getSize()),
                page.getTotal(), page.getCurrent(), page.getSize());
        return Result.success(result);
    }

    @Override
    public Result approval(SysSupplierApprovalReq req) {

        if (req.getApprovalId() == null) {
            return Result.failed(SystemError.SYS_402);
        }
        if (!ApprovalStatus.isCheckStatus(req.getApprovalStatus())) {
            return Result.failed(SystemError.SYS_402);
        }

        //查询供应商信息
        QueryWrapper<SysSupplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysSupplier::getId, req.getBusinessId())
                .eq(SysSupplier::getIsDeleted, IsDeletedCode.NO);
        SysSupplier supplier = sysSupplierMapper.selectOne(queryWrapper);
        if (supplier == null) {
            return Result.failed(SystemError.SYS_411);
        }

        /**
         * 审批
         */
        Result<ApprovalCheckDTO> result = sysApprovalService.check(req.getApprovalId(), req.getUserId(),
                req.getApprovalStatus(), req.getRemark());
        if (!result.isSuccess()) {
            SystemError systemError = SystemError.getDefined(result.getCode());
            return Result.failed(systemError);
        }
        if (result.getData() == null || !result.getData().getIsFinish()) {
            return Result.success();
        }

        //审批状态（0：撤回，4：审批不通过，3：审批通过）
        if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_YES.getCode()) {
            //审批通过
            supplier.setCheckStatus(SupplierAddCheckStatus.REVIEW_YES.getCode());
            supplier.setStatus(SupplierStatus.ENABLE.getCode());

        } else if (req.getApprovalStatus() == SupplierAddCheckStatus.REVIEW_NO.getCode()) {
            //审批不通过
            supplier.setCheckStatus(SupplierAddCheckStatus.REVIEW_NO.getCode());
            supplier.setStatus(SupplierStatus.DISABLE.getCode());
        } else {
            //撤回
            supplier.setCheckStatus(SupplierAddCheckStatus.SAVED.getCode());//已保存
            supplier.setStatus(SupplierStatus.DISABLE.getCode());
        }
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        supplier.setModifiedId(req.getUserId());
        supplier.setGmtModified(nowLocalDateTime);
        sysSupplierMapper.updateById(supplier);
        return Result.success();

    }

    @Override
    public Result updateStatus(SysSupplierUpdateStatusReq req) {
        SysSupplier supplier = baseMapper.selectById(req.getId());
        if (supplier == null) {
            throw new BusinessException(SystemError.SYS_411);
        }
        //如果改为有效状态
        if (req.getNewStatus() == SupplierStatus.ENABLE.getCode()) {
            //审批状态不是审批通过的其他状态下不能修改为有效状态
            if (supplier.getCheckStatus() != SupplierAddCheckStatus.REVIEW_YES.getCode()) {
                throw new BusinessException(SystemError.BIG_CLIENBIG_CLIENT_6001T_6006);
            }
        }

        supplier.setStatus(req.getNewStatus());
        LocalDateTime nowLocalDateTime = LocalDateTime.now();
        supplier.setModifiedId(req.getUserId());
        supplier.setGmtModified(nowLocalDateTime);
        sysSupplierMapper.updateById(supplier);
        return Result.success();
    }

    @Override
    public Result deleteById(Long id) {
        return baseMapper.deleteById(id) > 0 ? Result.success() : Result.failed(SystemError.CMS_23001);
    }

    @Override
    public Result<List<SysSupplierQueryListDTO>> queryListByItemId(Long itemId) {
        QueryWrapper<SysSupplierCostItem> qw = new QueryWrapper();
        qw.lambda().eq(SysSupplierCostItem::getCostItemId, itemId)
                .eq(SysSupplierCostItem::getIsDeleted, IsDeletedCode.NO.getCode());
        List<SysSupplierCostItem> ssci = sysSupplierCostItemMapper.selectList(qw);
        if (CollectionUtils.isNotEmpty(ssci)) {
            Set<Long> sids = ssci.stream().map(e -> e.getSupplierId()).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(sids)) {
                QueryWrapper<SysSupplier> ssqw = new QueryWrapper();
                //审批状态采用公共的枚举
                ssqw.lambda().in(SysSupplier::getId, sids)
                        .eq(SysSupplier::getCheckStatus, ApprovalStatus.REVIEW_YES.getCode())
                        .eq(SysSupplier::getStatus, SupplierStatus.ENABLE.getCode())
                        .eq(SysSupplier::getIsDeleted, IsDeletedCode.NO.getCode());
                List<SysSupplier> sysSuppliers = baseMapper.selectList(ssqw);
                if (CollectionUtils.isNotEmpty(sysSuppliers)) {
                    List<SysSupplierQueryListDTO> ssql = EntityUtil.copyList(sysSuppliers, SysSupplierQueryListDTO.class);
                    return Result.success(ssql);
                }
            }
        }
        return Result.success(null);
    }

    private void addItems(List<AddSupplierCostItemReq> itemReqList, Long supplierId, Long userId) {
        LocalDateTime now = LocalDateTime.now();
        for (AddSupplierCostItemReq itemReq : itemReqList) {
            SysSupplierCostItem supplierCostItem = EntityUtil.copy(itemReq, SysSupplierCostItem.class);
            // 供应商成本项id
            long SupplierCostItemId = SnowflakeIdWorker.nextId();
            supplierCostItem.setId(SupplierCostItemId);
            supplierCostItem.setSupplierId(supplierId);
            supplierCostItem.setGmtCreate(now);
            int insert = sysSupplierCostItemMapper.insert(supplierCostItem);
            if(insert > 0){
                if(itemReq.getCostItemDepartmentReqList() != null && itemReq.getCostItemDepartmentReqList().size() > 0){
                    for (CostItemDepartmentReq item: itemReq.getCostItemDepartmentReqList()) {
                        SysSupplierCostItemDepartment itemDepartment = new SysSupplierCostItemDepartment();
                        itemDepartment.setDepartmentId(item.getDepartmentId());//部门ID
                        itemDepartment.setDepartmentName(item.getDepartmentName());//部门名称
                        itemDepartment.setGmtCreate(now);
                        itemDepartment.setCreateId(userId);
                        itemDepartment.setId(SnowflakeIdWorker.nextId());
                        // 所属部门 与供应商成本项id 一对一
                        itemDepartment.setItemId(SupplierCostItemId);
                        sysSupplierCostItemDepartmentMapper.insert(itemDepartment);
                    }
                }
            }
        }
    }
}


